﻿using System;
using System.ComponentModel;
using System.Linq;

namespace Sayook.Framework.Tools
{
    /// <summary>
    /// 枚举 扩展类
    /// </summary>
    public static class EnumHelper
    {
        /// <summary>
        /// 获取枚举字段的属性描述;
        /// 如果没有设置该属性则返回枚举值名称
        /// </summary>
        /// <param name="item">枚举值</param>
        /// <returns>属性描述</returns>
        public static string Description(this Enum item)
        {
            var itemName = item.ToString();
            var field = item.GetType().GetField(itemName);
            var attrs = field?.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
            if (attrs?.Any() == true)
            {
                return attrs[0].Description;
            }

            return itemName;
        }
    }
}